#include <QDateTime>
#include <QTime>
#include <QDebug>

#include "inc\qlog.h"

QLog* QLog::instance = NULL;

QLog::QLog(QObject *parent) :
    QObject(parent),
    file(new QFile ("metadata.log", this))
{
    //int i = 0;
    //while (file->exists() && i >= 0) {
    //    file->setFileName(QString("metadata-")+QString::number(i++)+QString(".log"));
    //}
    if (!file->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text | QIODevice::Truncate)) {
        qDebug() << "Error openning log file.";
    }
    out.setDevice(file);
    out << QDateTime::currentDateTime().toString() << "\n\n";
    out.flush();
}

QLog::~QLog() {
    out.flush();
    file->close();
}

QLog* QLog::get() {
    if (instance == NULL) {
        instance = new QLog();
    }
    return instance;
}

void QLog::log(const char* message) {
    get()->write(message);
}

void QLog::log(const QString& message) {
    get()->write(message);
}

void QLog::log(const QByteArray& message) {
    get()->write(message);
}

/*
QLog& QLog::operator<<(const QByteArray& message) {

    return *get();
}
*/

void QLog::write(const char* message) {
    write(QByteArray(message));
}

void QLog::write(const QString& message) {
    write(message.toUtf8());
}

void QLog::write(const QByteArray& message) {
    if (file) {
        out << QTime::currentTime().toString() << ": " << message << "\n";
        out.flush();
    }
}
